package com.example.testone.utils

import com.example.testone.viewModels.SettingViewModel
import me.f1reking.serialportlib.SerialPortHelper
import me.f1reking.serialportlib.listener.IOpenSerialPortListener
import me.f1reking.serialportlib.listener.ISerialPortDataListener
import me.f1reking.serialportlib.listener.Status
import java.io.File
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.concurrent.thread

//interface TTLSerialCallBackEvent{
//    fun callbackData(bytes:ByteArray?)
//}


@Singleton
class MySerialPort @Inject constructor(){
    companion object{
        val TAG = "---!!"
    }
    //尝试重连

    var lastConnTimeStamp = 0;

    val serialPort:SerialPortHelper
//    var iSerialPortDataListener: ISerialPortDataListener?=null
//    var iOpenSerialPortListener: IOpenSerialPortListener?=null
    init {

        serialPort = SerialPortHelper
            .Builder("/dev/ttyS1",9600)
            .build()

//        serialPort.setIOpenSerialPortListener(iOpenSerialPortListener)
//
//        serialPort.setISerialPortDataListener(iSerialPortDataListener)

//        open()
    }

    //尝试重连
    fun resetConn()
    {
        val currentTimeStamp = Helper.getCurrentTimeStamp();
        //防止频繁断开重连 5秒期限
        if(currentTimeStamp - lastConnTimeStamp < 5){
            return
        }
        MyLog.print(TAG,"resetConn：open:${currentTimeStamp}-")
        //重置时间
        lastConnTimeStamp = currentTimeStamp

        if(serialPort.isOpen){
            serialPort.close()
        }
        //开启设备
        Timer().schedule(object: TimerTask(){
            override fun run() {
                //重连
                serialPort.open()
            }
        },500)


    }

    fun open(){
        val bool = serialPort.open()
        MyLog.print(TAG,"open:${bool}")

    }
    //關閉串口
    fun close(){
        serialPort.close()
        MyLog.print(TAG,"close:")

    }

}